package org.piggy.server.rpc.spring;

import org.piggy.common.anno.Remote;
import org.piggy.server.rpc.core.Mediator;
import org.piggy.server.rpc.core.MethodBean;
import org.piggy.server.rpc.server.NettyServer;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;

@Component
public class NettyRefreshedListener implements ApplicationListener<ContextRefreshedEvent>, Ordered {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        Thread thread = new Thread(NettyServer::start);
        thread.setDaemon(false);
        thread.start();

        Map<String, Object> beansWithAnnotation = contextRefreshedEvent.getApplicationContext().getBeansWithAnnotation(Remote.class);
        Collection<Object> beans = beansWithAnnotation.values();
        for(Object bean : beans){
            Method[] declaredMethods = bean.getClass().getDeclaredMethods();
            for(Method method : declaredMethods){
                String name = bean.getClass().getInterfaces()[0].getName() + "." + method.getName();
                MethodBean methodBean = new MethodBean();
                methodBean.setBean(bean);
                methodBean.setMethod(method);
                Mediator.methodBeanMap.put(name, methodBean);
            }
        }
    }

    @Override
    public int getOrder() {
        return -1;
    }

}
